package com.yc.web.controller;

import com.yc.bean.User;
import com.yc.services.UserService;
import com.yc.utils.JwtUtil;
import com.yc.web.controller.model.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/user")
public class UserController {
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public ResponseResult register(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            @RequestParam("email") String email,
            @RequestParam("avatar") String avatar
    ) {
        // 1. 校验参数
        if (username == null || username.trim().isEmpty()) {
            return ResponseResult.error("用户名不能为空");
        }
        if (password == null || password.trim().isEmpty()) {
            return ResponseResult.error("密码不能为空");
        }
        if (email == null || email.trim().isEmpty()) {
            return ResponseResult.error("邮箱不能为空");
        }

        Boolean register = userService.register(username, password, email, avatar);
        if (!register) {
            return ResponseResult.error("注册失败,用户名或者邮箱已经存在");
        }
        return ResponseResult.ok("注册成功");
    }

    @PostMapping("/login")
    public ResponseResult login(
            @RequestParam("username") String username,
            @RequestParam("password") String password
    ) {
        // 1. 校验参数
        if (username == null || username.trim().isEmpty()) {
            return ResponseResult.error("用户名不能为空");
        }
        if (password == null || password.trim().isEmpty()) {
            return ResponseResult.error("密码不能为空");
        }

        // 2. 查找用户并校验密码
        User user = userService.login(username, password);
        if (user == null) {
            return ResponseResult.error("用户名或密码错误");
        }

        // 3. 生成JWT Token
        String token = jwtUtil.generateToken(username);

        // 4. 返回用户信息和token
        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        data.put("user", user);

        return ResponseResult.ok().setData(data);
    }

    @GetMapping("/profile")
    public ResponseResult profile(@RequestHeader("Token") String token) {
        try {
            // 1. 校验token
            if (!jwtUtil.validateToken(token)) {
                return ResponseResult.error("Token无效");
            }

            // 2. 解析token获取用户名
            String username = jwtUtil.getUsernameFromToken(token);

            // 3. 获取用户信息
            User user = userService.getUserByUsername(username);
            if (user == null) {
                return ResponseResult.error("用户不存在");
            }

            // 4. 返回用户信息（不包含密码）
            user.setPassword(null);
            return ResponseResult.ok().setData(user);
        } catch (Exception e) {
            return ResponseResult.error("获取用户信息失败");
        }
    }

    @PostMapping("/updateProfile")
    public ResponseResult updateProfile(
            @RequestHeader("Token") String token,
            @RequestParam(value = "email", required = false) String email,
            @RequestParam(value = "avatar", required = false) String avatar,
            @RequestParam(value = "tags", required = false) String tags,
            @RequestParam(value = "interests", required = false) String interests
    ) {
        try {
            // 1. 校验token
            if (!jwtUtil.validateToken(token)) {
                return ResponseResult.error("Token无效");
            }

            // 2. 解析token获取用户名
            String username = jwtUtil.getUsernameFromToken(token);

            // 3. 更新用户信息
            Boolean success = userService.updateProfile(username, email, avatar, tags, interests);
            if (!success) {
                return ResponseResult.error("更新失败");
            }

            return ResponseResult.ok("更新成功");
        } catch (Exception e) {
            return ResponseResult.error("更新失败");
        }
    }

    @PostMapping("/changePassword")
    public ResponseResult changePassword(
            @RequestHeader("Token") String token,
            @RequestParam("currentPassword") String currentPassword,
            @RequestParam("newPassword") String newPassword
    ) {
        try {
            // 1. 校验token
            if (!jwtUtil.validateToken(token)) {
                return ResponseResult.error("Token无效");
            }

            // 2. 解析token获取用户名
            String username = jwtUtil.getUsernameFromToken(token);

            // 3. 校验新密码
            if (newPassword == null || newPassword.trim().isEmpty() || newPassword.length() < 6) {
                return ResponseResult.error("新密码长度至少6位");
            }

            // 4. 修改密码
            Boolean success = userService.changePassword(username, currentPassword, newPassword);
            if (!success) {
                return ResponseResult.error("当前密码错误");
            }

            return ResponseResult.ok("密码修改成功");
        } catch (Exception e) {
            return ResponseResult.error("密码修改失败");
        }
    }

    @DeleteMapping("/deleteAccount")
    public ResponseResult deleteAccount(@RequestHeader("Token") String token) {
        try {
            // 1. 校验token
            if (!jwtUtil.validateToken(token)) {
                return ResponseResult.error("Token无效");
            }

            // 2. 解析token获取用户名
            String username = jwtUtil.getUsernameFromToken(token);

            // 3. 删除账户
            Boolean success = userService.deleteAccount(username);
            if (!success) {
                return ResponseResult.error("删除账户失败");
            }

            return ResponseResult.ok("账户删除成功");
        } catch (Exception e) {
            return ResponseResult.error("删除账户失败");
        }
    }
}